package com.kmu.kmucampus.Fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kmu.kmucampus.R;
import com.kmu.kmucampus.activity.MainActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.ApiResponse;
import mytest.ssw.www.core.sqLiteTools;
import mytest.ssw.www.mylibrary.DeptNode;
import mytest.ssw.www.mylibrary.Student;
import mytest.ssw.www.mylibrary.StudentInfo;



/**
 * Created by 73409 on 2015/10/22.
 */
public class SettingFragment extends Fragment {
    static String TB_STU;
    ApiResponse<StudentInfo> userInfo;
    String gender;
    String birth;
    private String TAG = "SettingFragment";
    private TextView tv_No;
    private TextView tv_num;   //
    private  TextView tv_name;
    private  TextView tv_className;
    private  TextView tv_gender;
    private  TextView tv_phone;
  //  private  TextView tv_birthday;
    private TextView  tv_dorm;
    private  TextView text_class;
    private RadioButton rb_Femle;
    private RadioButton rb_Male;
    private RadioGroup rg_Gender;
    //   private LayoutInflater inflater;
    private EditText  Et_stuNum;
    private EditText  Et_stuName;
    private EditText  Et_phoneNum;
    private  EditText Et_gender;
//    private  TextView Et_birthday;
    private EditText Et_dorm;
    private  EditText Et_class;
    private Button btn_setUserInfo;
    private  View vw;
    StudentInfo stuInfo;
    String accounts;
    int flag;
    private SharedPreferences sp;
    SharedPreferences.Editor spEitor;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //     this.inflater=inflater;
        View view = inflater.inflate(R.layout.fragmentlsetting, container, false);
        vw=view;
        init();
        setInfo();
        if(tv_name.getText().toString()==null)
        { setInfo();}
        btn_setUserInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginDialog(inflater, getInfoSharePrefrence(accounts));

            }
        });
        return view;
    }




    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = getActivity().getSharedPreferences("KMUCampusLogInfo", Context.MODE_PRIVATE);
        spEitor=sp.edit();
        accounts = getActivity().getIntent().getExtras().getString("account");  //   Toast.makeText(this, "学号" + account, Toast.LENGTH_SHORT).show();
        TB_STU="TB_STU";
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    void setInfo(){
        final String account = accounts;  //   Toast.makeText(this, "学号" + account, Toast.LENGTH_SHORT).show();
        sqLiteTools sqlTool=new sqLiteTools(getActivity().getFilesDir().toString());
        stuInfo = getInfoSharePrefrence(accounts);
      //  String CONNECT_TYPE=((MainActivity) getActivity()).appAction.getNetworkInfo(getContext());
    //    Log.d("CONNECT_TYPE", "" + CONNECT_TYPE);
        if( stuInfo==null) {
            ((MainActivity) getActivity()).appAction.GetSomeoneInfor(account, new ActionCallbackListener<ApiResponse<StudentInfo>>() {
                @Override
                public void onSuccess(ApiResponse<StudentInfo> data) {
                    putData(data.getStudentInfo());
                    putClassName(data.getStudentInfo().getDepartmentNum());
                    Log.d("setInfo:deptnum=", data.getStudentInfo().getDepartmentNum());
                    putInfoToSharePrefrence(data.getStudentInfo());
                  }
                @Override
                public void onFailure(String errorEvent, String element) {
                    Toast.makeText(getActivity(), errorEvent, Toast.LENGTH_SHORT).show();
                }
            });

        }else {
                Log.d("setInfo", "-----" + stuInfo.getName());
                putData(stuInfo);
                putClassName(stuInfo.getDepartmentNum());
        }
    }

    public void init(){
//        tv_birthday=(TextView) vw.findViewById(R.id.tv_birthday);
//        tv_birthday.setVisibility(View.GONE);
 //       TextView tv_bir=(TextView) vw.findViewById(R.id.tv_birth);
 //       tv_bir.setVisibility(View.GONE);
        tv_name = (TextView) getActivity().findViewById(R.id.tv_userName);
        tv_num = (TextView) vw.findViewById(R.id.tv_StuNum);
        tv_phone = (TextView) vw.findViewById(R.id.tv_Phone);
        tv_gender = (TextView) vw.findViewById(R.id.tv_Gender);
        tv_dorm = (TextView) vw.findViewById(R.id.tv_dorm);
        btn_setUserInfo= (Button) vw.findViewById(R.id.btn_setUserInfo);
        tv_className=(TextView) vw.findViewById(R.id.tv_className);
        tv_No = (TextView) vw.findViewById(R.id.tvNum);//工号或学号
        if(accounts.length()<=5){
            tv_No.setText("工号：");
        }
    }

    public void putData(StudentInfo data){
        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(getContext().TELEPHONY_SERVICE);
        String IMEI = tm.getDeviceId();
        String TEL = null;//tm.getLine1Number();
        tv_name.setText("欢迎你：" + data.getName() + "");
        Log.d("putData", "" + data.getNum());
        tv_num.setText(data.getNum() + "");
        if (data.getGender().length() <= 4) {
            gender = "男";
        } else {
            gender = "女";
        }
        tv_gender.setText(gender + "");
//        Log.d("birth_long", data.getBirthday());
        if(data.getDormitory()!=null) {tv_dorm.setText(data.getDormitory());}
        else{tv_dorm.setVisibility(View.GONE);}

      if(data.getBirthday()!=null) {
          long birth_long = Long.parseLong(data.getBirthday());
          Date birth_date = new Date(birth_long);
          Log.d("birth_date", birth_date.toString());
          birth = new SimpleDateFormat("yyyy-MM-dd").format(birth_date);
        /*  if (tv_birthday == null) {
              Log.d("tv_birthday", "is null");
          } else tv_birthday.setText(birth);*/
      }
            if(data.getPhoneNum()!=null) { tv_phone.setText(data.getPhoneNum());
        }
        else{
            if(TEL!=null) {
                data.setPhoneNum(TEL);
                tv_phone.setText(data.getPhoneNum());
            }
        }

    }



    public void LoginDialog (LayoutInflater inflater,final StudentInfo data) {
       /* this.mContext = context;
        //动态加载布局生成View对象
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);*/
        View settingDialogView = inflater.inflate(R.layout.setting_dialog, null);
        Et_stuName=(EditText) settingDialogView.findViewById(R.id.edit_stuName);
        Et_phoneNum=(EditText) settingDialogView.findViewById(R.id.edit_phoneNum);
        Et_stuNum=(EditText) settingDialogView.findViewById(R.id.edit_stuNum);
        rb_Femle=(RadioButton) settingDialogView.findViewById(R.id.rbFemale);
        rb_Male=(RadioButton) settingDialogView.findViewById(R.id.rbMale);
        rg_Gender=(RadioGroup) settingDialogView.findViewById(R.id.rg_Gender);
       // Et_gender=(EditText) settingDialogView.findViewById(R.id.edit_gender);
      //  Et_birthday=(TextView) settingDialogView.findViewById(R.id.edit_birth);
        Et_class=(EditText) settingDialogView.findViewById(R.id.edit_class);
        Et_dorm=(EditText) settingDialogView.findViewById(R.id.edit_dorm);
        text_class=(TextView) settingDialogView.findViewById(R.id.text_class);
        Et_stuNum.setText(data.getNum());
        Et_phoneNum.setText(data.getPhoneNum());
        Et_stuName.setText(data.getName());
        if (data.getGender().length() <= 4) {
            rb_Male.setChecked(true);
        } else {
           rb_Femle.setChecked(true);
        }
//        Et_gender.setText(this.gender);
  //      Et_birthday.setText(this.birth);
//     Et_class.setText(data.getStudentInfo().get);
        Et_class.setVisibility(View.GONE);
        text_class.setVisibility(View.GONE);
        Et_dorm.setText(data.getDormitory());

        //创建一个AlertDialog对话框
        AlertDialog.Builder  longinDialog = new AlertDialog.Builder(getActivity())
                .setTitle("修改个人信息")
                .setView(settingDialogView)                //加载自定义的对话框式样
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d("取消：", Integer.toString(which));
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //  StudentInfo stu=new Student(data.getStudentInfo());
                        modifyStuInfo(data);
                        Log.d("确定：", Integer.toString(which));

                    }
                });

        longinDialog.show();
    }
    public void modifyStuInfo(final StudentInfo stu){
        stu.setNum(Et_stuNum.getText().toString());
        stu.setName(Et_stuName.getText().toString());
        stu.setPhoneNum(Et_phoneNum.getText().toString());
      //  stu.setGender(Et_gender.getText().toString());
     //   stu.setBirthday(Et_birthday.getText().toString());
        stu.setDormitory(Et_dorm.getText().toString());
                //Et_class.getText().toString());
        rg_Gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup rg, int checkedId) {
                // TODO Auto-generated method stub
                if (checkedId == rb_Male.getId()) {
                stu.setGender("male");
                        } else if (checkedId == rb_Femle.getId()) {

                } else {
                    stu.setGender("femal");
                }
            }
        });
        final StudentInfo stud=stu;
        ((MainActivity) getActivity()).appAction.modifyStuInfo(stud, new ActionCallbackListener<ApiResponse<Student>>() {
            @Override
            public void onSuccess(ApiResponse<Student> data) {
//               Log.d("SetFrg—modifyStu:",data.getStudent().getName());
                StudentInfo stuInfo=new StudentInfo().stuToStuInfo(data.getStudent());
                putData(stuInfo);
                putInfoToSharePrefrence(stuInfo);
            }
            @Override
            public void onFailure(String errorEvent, String element) {
                Toast.makeText(getActivity(), errorEvent, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void putClassName(final String BMnum){
           sqLiteTools sqlTools = new sqLiteTools(getActivity().getFilesDir().toString());
          //  Log.d("setInfoToDB", Integer.toString(sqlTools.getStuInfoFrDB(TB_STU, null).size()));
        List<DeptNode> dept=sqlTools.getDeptByNum("TB_DEPT", BMnum);
        if(dept.size()==0) {
            Log.d("putClassName","getDept from net");
            ((MainActivity) getActivity()).appAction.GetDeptNodeList(new ActionCallbackListener<List<DeptNode>>() {
                @Override
                public void onSuccess(List<DeptNode> data) {
                    int i = 0, flag = 1;
                    for (i = 0; i < data.size() && flag != 0; i++) {//      Log.i(i+":"+data.get(i).getNum(),""+BMnum);
                        if (data.get(i).getNum().equals(BMnum)) {
                            Log.i("putClassName:" + Integer.toString(i), "--");
                            flag = 0;
                        }
                    }
                    i = --i;
                    Log.i("getClass:" + Integer.toString(i), "--" + data.size());
                    tv_className.setText(data.get(i).getFullName());
                }
                @Override
                public void onFailure(String errorEvent, String element) {
                    Toast.makeText(getActivity(), "修改失败，请检查网络连接。", Toast.LENGTH_SHORT).show();
                }
            });
        }
        else  {
            tv_className.setText(dept.get(0).getFullName());
        }
    }
    public HashSet<String> putInfoToSharePrefrence(StudentInfo stuInfo){
        Gson gson=new Gson();
        boolean flag = false;
        String accountJson=sp.getString("accontJson", null);
        HashSet<String> accountSet=gson.fromJson(accountJson, new TypeToken<HashSet<String>>() {
        }.getType());
        if(stuInfo!=null) {
            if(stuInfo.getNum()!=null)
                if(accountSet==null) {
                    accountSet=new HashSet<>();
                    accountSet.add(stuInfo.getNum());
                }
            accountJson = gson.toJson(accountSet);
            String stuJson = gson.toJson(stuInfo);
            Log.d("putInfoToShareP_stuJson", "------" + stuJson);
            spEitor.putString(stuInfo.getNum(), stuJson);
            Log.d("putInfoToShareP_stuNum", "------" + stuInfo.getNum());
            spEitor.putString("accontSet", accountJson);
            Log.d("accontSet", "------" + accountJson);
            spEitor.commit();
        }
        return accountSet;
    }
    public StudentInfo getInfoSharePrefrence(String account) {
        String stuJson = sp.getString(""+account, null);
        Log.d("getInfoShareP_account", "--" + account);
        Log.d("getInfoShareP_stuJson", "--" + stuJson);
        if (stuJson == null) return null;
        else {
            Gson gson = new Gson();
            StudentInfo stuInfo = null;
            if (stuJson != null) {
                stuInfo = gson.fromJson(stuJson, new TypeToken<StudentInfo>() {
                }.getType());
            }
            return stuInfo;
         }
    }
    }

//     test_button = (Button) getActivity().findViewById(R.id.test_button);
//   test_button.setOnClickListener(new myonclick());
   /* class myonclick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).appAction.Getsomeoneinfor("201311010ff");*/
            /*, new ActionCallbackListener<StudentInfo>() {
                @Override
                public void onSuccess(StudentInfo data) {
                    Log.v("onSuccess", data.getName());
                }

                @Override
                public void onFailure(String errorEvent, String message) {
                    Log.v("onFailure", message);
                }
            });
*/





